package com.itheima.comment.service.impl;

import com.itheima.comment.document.Comment;
import com.itheima.comment.dto.CommentSaveDto;
import com.itheima.comment.repository.CommentRepository;
import com.itheima.comment.service.CommentService;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.comment.service.impl
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    /**
     * 发表评论
     *
     * @param dto
     */
    @Override
    public void save(CommentSaveDto dto) {
        //1. 判断是否为匿名
        if(RequestContextUtil.isAnonymous()){
            throw new LeadNewsException(HttpCodeEnum.NEED_LOGIN);
        }
        //2. 构建Pojo
        int loginUserId = Integer.parseInt(RequestContextUtil.getUserId());
        Comment comment = new Comment();
        BeanUtils.copyProperties(dto,comment);
        comment.setLikes(0);
        comment.setReplys(0);
        comment.setCreatedTime(LocalDateTime.now());
        comment.setUserId(Long.valueOf(loginUserId));
        comment.setHeadImage(RequestContextUtil.getHeader(SystemConstants.LOGIN_USER_IMAGE));
        comment.setNickName(RequestContextUtil.getHeader(SystemConstants.LOGIN_USER_NAME));
        comment.setCreatedTime(LocalDateTime.now());
        comment.setUpdatedTime(LocalDateTime.now());
        //3. 保存
        commentRepository.save(comment);
    }
}
